﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IISLogAnalyzer.Model.Entities;

namespace IISLogAnalyzer.Data.Providers.WebLogProvider
{
    public static class HelpFuncs
    {
        public static List<W3CLogging> ResolveAllBrowserNames(List<W3CLogging> orinalData)
        {
            string longName = string.Empty;

            foreach (W3CLogging item in orinalData)
            {
                if (item.cs_ua != null && item.cs_ua != string.Empty)
                {
                    if (item.cs_ua.Length > 3)
                    {
                        // analyze browser name
                        item.cs_ua = ResolveBrowserName(item.cs_ua);
                    }
                    else
                        item.cs_ua = "unknown";
                }
            }

            return orinalData;
        }

        private static string ResolveBrowserName(string longName)
        {
            string browser = "unknown";
            string version = string.Empty;
            string[] browserInfo;

            if (longName.Contains("MSIE"))
            {
                if (longName.Contains(';'))
                {
                    browserInfo = longName.Split(';');

                    if (browserInfo.Length > 0)
                    {
                        foreach (string item in browserInfo)
                        {
                            if (item.StartsWith("+MSIE"))
                            {
                                browser = "Microsoft Internet Explorer " + item.Replace("+MSIE+", "");
                            }
                        }
                    }
                }
                else
                    browser = "Microsoft Internet Explorer";
            }
            if (longName.Contains("FireFox"))
                browser = "FireFox";
            if (longName.Contains("Googlebot"))
                browser = "Googlebot";
            if (browser == "unknown" && longName.Contains(';'))
            {
                browserInfo = longName.Split(';');

                if (browserInfo.Length > 0)
                {
                    string item = browserInfo[1];
                    if (item != null)
                        browser = item.Replace("+", " ");
                }
            }

            if (browser != "unknown" && browser.Length < 3)
            {
                browser = "unknown"; // there can be veird short names in log
            }

            return browser;
        }

    }
}
